//
//  ZZCLoginController.m
//  ZZC-Finance
//
//  Created by mac on 2017/5/21.
//  Copyright © 2017年 mac. All rights reserved.
//
#define WX_APPKEY @"wxfed981e2b05e1fab"

#import "ZZCLoginController.h"
#import "ZZCRegisterOneController.h"
#import "ZZCForgetPasswordOneController.h"
#import "ZZCMeController.h"
#import "ZZCRegisterOneController.h"
#import "ZZCHomeController.h"
#import "ZZCClassifyController.h"
#import "ZZCShoppingController.h"
#import "ZZCLatestController.h"
#import "WXApi.h"
#import "WXApiObject.h"
#import "AppDelegate.h"
#import "WXApiManager.h"
#import "ZZCWXLoginView.h"
#import "ZZCWXLoginViewA.h"

//        self.WXImg = dic[@"headimgurl"];
//        self.WXName = dic[@"nickname"];
//        self.openID = dic[@"openid"];

@interface ZZCLoginController ()<UITextFieldDelegate,WXApiManagerDelegate>
@property (strong, nonatomic) AppDelegate *appdelegate;
@property (strong, nonatomic) ZZCWXLoginView *wxLoginView;
@property (strong, nonatomic) ZZCWXLoginViewA *wxLoginViewA;
@property (copy,   nonatomic) NSString *WXImg;
@property (copy,   nonatomic) NSString *WXName;
@property (copy,   nonatomic) NSString *openID;
@end

@implementation ZZCLoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"正资产账户登录";
//    self.phoneTextField.text = @"13512345678";
//    self.passwordTextField.text = @"12345678901";
//    self.phoneTextField.text = @"18745703072";
//    self.passwordTextField.text = @"123456";
//    self.phoneTextField.text = @"13555555555";
//    self.passwordTextField.text = @"qqqqqq";
//            self.phoneTextField.text = @"14712345678";
//            self.passwordTextField.text = @"qqqqqq";
    self.phoneTextField.text = ZZCNSUserDefaults(@"userphone");
//    self.passwordTextField.text = @"qqqqqq";
    self.phoneTextField.delegate = self;
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
//注册
- (IBAction)registerClick {
    ZZCLog(@"点击注册");
    ZZCRegisterOneController *reg = [ZZCRegisterOneController new];
    [self.navigationController pushViewController:reg animated:YES];
}
//忘记密码
- (IBAction)forgetPasswordClick {
    ZZCLog(@"点击忘记密码");
    ZZCForgetPasswordOneController *one = [ZZCForgetPasswordOneController new];
    [self.navigationController pushViewController:one animated:YES];
}
- (void)weChatCallBackWithCode:(NSString *)code{
    NSString *urlString =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WX_APPKEY,@"bb2780d0088f8bd5272e0b7649804250",code];
    __block ZZCLoginController *loginVC = self;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dic);
        [loginVC getUserInfoWithAccessToken:[dic objectForKey:@"access_token"] andOpenId:[dic objectForKey:@"openid"]];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
    
    
}

//wx获取用户信息
- (void)getUserInfoWithAccessToken:(NSString *)accessToken andOpenId:(NSString *)openId{
    NSString *urlString =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",accessToken,openId];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        //保存数据
        
        self.WXImg = dic[@"headimgurl"];
        self.WXName = dic[@"nickname"];
        self.openID = dic[@"openid"];
        [self clickSignIn];
        NSLog(@"%@",dic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}

- (void)managerDidRecvAuthResponse:(SendAuthResp *)response
{
    [self weChatCallBackWithCode:response.code];
}

//微信登录
- (IBAction)weixinClick {
    ZZCLog(@"点击微信登录");
    SendAuthReq *req = [[SendAuthReq alloc] init];
    req.scope = @"snsapi_userinfo";
    req.state = @"App";
    [WXApiManager sharedManager].delegate = self;
    [WXApi sendReq:req];
    
//    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:nil completion:^(id result, NSError *error) {
//        if (error) {
//            NSLog(@"%@",error);
//        } else {
//            self.resp = result;
//            ZZCLog(@"---%@",self.resp.openid);
//            ZZCLog(@"--%@",self.resp.iconurl);
//            NSDictionary *dict = @{@"open_id":self.resp.openid};
//            NSString *sign = [ZZCRequest getSignWithDict:dict];
//            sign = [NSString md5:[sign lowercaseString]];
//            NSDictionary *param = @{@"timestamp":[NSString timeStr],@"sign":sign,@"open_id":self.resp.openid};
//            [[ZZCRequest sharedNetworkTools] POST:ZZCURL_API_WXLOGIN parameters:param finished:^(id  _Nullable responseObject, NSError * _Nullable error) {
//                if (error) {
//                    ZZCLog(@"失败-%@",error);
//                }else {
//                    ZZCLog(@"-%@",responseObject);
//                    if ([responseObject[@"code"] integerValue] == 400) {
//                        ZZCRegisterOneController *one = [ZZCRegisterOneController new];
//                        one.openId = self.resp.openid;
//                        one.iconUrl = self.resp.iconurl;
//                        [self.navigationController pushViewController:one animated:YES];
//                    } else {
//                        //存储全局的token
//                        NSUserDefaults *store =  [NSUserDefaults standardUserDefaults];
//                        [store setObject:responseObject[@"data"] forKey:@"USERPARAM"];
//                        [store setObject:responseObject[@"data"][@"token"] forKey:@"token"];
//                        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//                        [user setBool:YES forKey:@"isLogin"];
//                        
//                        for (UIViewController *controller in self.navigationController.viewControllers) {
//                            if ([controller isKindOfClass:[ZZCMeController class]]) {
//                                [self.navigationController popToViewController:controller animated:YES];
//                                //这里可以做回到登录界面的一些数据操作
//                                [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSucceed" object:self];
//                                
//                            }
//                        }
//                    }
//                    
//                }
//            }];
//            
//        }
//    }];
    
}
- (void)clickSignIn {
        NSDictionary *dict = @{@"open_id":self.openID};
        NSString *sign = [ZZCRequest getSignWithDict:dict];
        sign = [NSString md5:[sign lowercaseString]];
        NSDictionary *param = @{@"timestamp":[NSString timeStr],@"sign":sign,@"open_id":self.openID};
        [[ZZCRequest sharedNetworkTools] POST:ZZCURL_API_WXLOGIN parameters:param finished:^(id  _Nullable responseObject, NSError * _Nullable error) {
            if (error) {
                ZZCLog(@"失败-%@",error);
            }else {
                ZZCLog(@"-%@",responseObject);
            if ([responseObject[@"code"] integerValue] == 400) {
//                [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                
                [self.view addSubview:self.wxLoginViewA];
                //zhuche
                [self.wxLoginViewA.registerBtn addTarget:self action:@selector(registerBtnClick) forControlEvents:UIControlEventTouchUpInside];
                //bangding
                [self.wxLoginViewA.binDingBtn addTarget:self action:@selector(binDingBtnAction) forControlEvents:UIControlEventTouchUpInside];

            } else {
                //存储全局的token
                NSUserDefaults *store =  [NSUserDefaults standardUserDefaults];
                [store setObject:responseObject[@"data"] forKey:@"USERPARAM"];
                [store setObject:responseObject[@"data"][@"token"] forKey:@"token"];
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                [user setBool:YES forKey:@"isLogin"];
                [store synchronize];
                
                for (UIViewController *controller in self.navigationController.viewControllers) {
                    if ([controller isKindOfClass:[ZZCMeController class]] || [controller isKindOfClass:[ZZCHomeController class]] || [controller isKindOfClass:[ZZCClassifyController class]] || [controller isKindOfClass:[ZZCLatestController class]] ||[controller isKindOfClass:[ZZCShoppingController class]]) {
                        [self.navigationController popToViewController:controller animated:YES];
                        //这里可以做回到登录界面的一些数据操作
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSucceed" object:nil];
                    }
                }
                        }
                        
                    }
                }];
}
- (void)registerBtnClick {
    [self.wxLoginViewA removeFromSuperview];
    ZZCRegisterOneController *one = [ZZCRegisterOneController new];
    one.openId = self.openID;
    one.iconUrl = self.WXImg;
    [self.navigationController pushViewController:one animated:YES];

}
- (void)binDingBtnAction {
    [self.wxLoginViewA removeFromSuperview];
    [self.view addSubview:self.wxLoginView];
    //bangding
    [self.wxLoginView.binDingBtn addTarget:self action:@selector(binDingBtnClick) forControlEvents:UIControlEventTouchUpInside];
    //zhuche
    [self.wxLoginView.registerBtn addTarget:self action:@selector(registerBtnClick) forControlEvents:UIControlEventTouchUpInside];


}
- (void)binDingBtnClick {
    if (_wxLoginView.userNumTFD.text == nil ) {
        [SVProgressHUD showInfoWithStatus:@"请检查手机号"];
        return;
    }
    if (_wxLoginView.passwordTFD.text == nil ) {
        [SVProgressHUD showInfoWithStatus:@"请检查密码"];
        return;
    }

    NSDictionary *dict = @{@"phone":_wxLoginView.userNumTFD.text,
                           @"password":_wxLoginView.passwordTFD.text,
                           @"open_id":self.openID};
    NSString *sign = [ZZCRequest getSignWithDict:dict];
    sign = [NSString md5:[sign lowercaseString]];
    NSDictionary *param = @{@"timestamp":[NSString timeStr],@"sign":sign,
                            @"phone":_wxLoginView.userNumTFD.text,
                            @"password":_wxLoginView.passwordTFD.text,
                            @"open_id":self.openID};
    [[ZZCRequest sharedNetworkTools] POST:ZZCURL_API_WXBINGDING parameters:param finished:^(id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            ZZCLog(@"失败-%@",error);
            //            [SVProgressHUD showInfoWithStatus:error[@""]];
        }else {
            ZZCLog(@"-____%@",responseObject);
            NSString *coed = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
            if ([coed isEqualToString:@"200"]) {
                //存储全局的token
                NSUserDefaults *store =  [NSUserDefaults standardUserDefaults];
                [store setObject:responseObject[@"data"] forKey:@"USERPARAM"];
                [store setObject:responseObject[@"data"][@"token"] forKey:@"token"];
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                [user setBool:YES forKey:@"isLogin"];
                [store synchronize];
                
                for (UIViewController *controller in self.navigationController.viewControllers) {
                    if ([controller isKindOfClass:[ZZCMeController class]] || [controller isKindOfClass:[ZZCHomeController class]] || [controller isKindOfClass:[ZZCClassifyController class]] || [controller isKindOfClass:[ZZCLatestController class]] ||[controller isKindOfClass:[ZZCShoppingController class]]) {
                        [self.navigationController popToViewController:controller animated:YES];
                        //这里可以做回到登录界面的一些数据操作
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSucceed" object:nil];
                    }
                }
                
                
            }
        }
    }];

}
//登录
- (IBAction)loginClick {
    ZZCLog(@"点击登录");
    [self login];
}
- (void)login {
    NSDictionary *dict = @{@"phone":self.phoneTextField.text,@"password":self.passwordTextField.text};
    NSString *sign = [ZZCRequest getSignWithDict:dict];
    sign = [NSString md5:sign];
    NSDictionary *param = @{@"timestamp":[NSString timeStr],@"sign":sign,@"phone":self.phoneTextField.text,@"password":self.passwordTextField.text};
    [[ZZCRequest sharedNetworkTools] POST:ZZCURL_API_LOGIN parameters:param finished:^(id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            ZZCLog(@"失败-%@",error);
//            [SVProgressHUD showInfoWithStatus:error[@""]];
        }else {
            ZZCLog(@"-____%@",responseObject);
            NSString *coed = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
            if ([coed isEqualToString:@"200"]) {
                //存储全局的token
                NSUserDefaults *store =  [NSUserDefaults standardUserDefaults];
                [store setObject:responseObject[@"data"] forKey:@"USERPARAM"];
                [store setObject:responseObject[@"data"][@"token"] forKey:@"token"];
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                [user setBool:YES forKey:@"isLogin"];
                [store synchronize];
                
                for (UIViewController *controller in self.navigationController.viewControllers) {
                    if ([controller isKindOfClass:[ZZCMeController class]] || [controller isKindOfClass:[ZZCHomeController class]] || [controller isKindOfClass:[ZZCClassifyController class]] || [controller isKindOfClass:[ZZCLatestController class]] ||[controller isKindOfClass:[ZZCShoppingController class]]) {
                        [self.navigationController popToViewController:controller animated:YES];
                        //这里可以做回到登录界面的一些数据操作
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSucceed" object:nil];
                    }
                }

            } else {
                [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
//                [self alertView];
            }
        }
    }];
}


- (void)alertView
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"登陆失败" message:@"帐号或密码错误，请重新输入" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    alert.alertViewStyle = UIAlertViewStyleDefault;
    [alert show];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
    if (textField == self.phoneTextField) {
        //用来做长度限制；
        if (range.location>=11) {
            return NO;
        }
    }
    if (textField == self.passwordTextField) {
        //用来做长度限制；
        if (range.location>=16) {
            return NO;
        }
    }
    return YES;
    
}
- (ZZCWXLoginView *)wxLoginView {
    if (_wxLoginView == nil) {
        _wxLoginView = [ZZCWXLoginView wxLoginView];
        _wxLoginView.frame = CGRectMake(0, 0, ZZCScreenW, ZZCScreenH);
        _wxLoginView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    }
    return _wxLoginView;
}
- (ZZCWXLoginViewA *)wxLoginViewA {
    if (_wxLoginViewA == nil) {
        _wxLoginViewA = [ZZCWXLoginViewA wxLoginView];
        _wxLoginViewA.frame = CGRectMake(0, 0, ZZCScreenW, ZZCScreenH);
        _wxLoginViewA.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    }
    return _wxLoginViewA;
}
@end
